//导入 express
const express = require("express");
const bodyParser = require("body-parser");
const UserModel = require("../db/models/UserModel");
const md5 = require("md5");
const {createToken} = require('../utils/token');

//创建路由对象
const router = express.Router();

// parse application/x-www-form-urlencoded    a=100&b=200
router.use(bodyParser.urlencoded({ extended: false }));

// parse application/json      {"a":100,"b": 200}
router.use(bodyParser.json());

//创建路由规则
router.post("/login", async (req, res) => {
  //获取客户端请求过来的请求体 body-parser
  let { username, pwd } = req.body;
  //校验用户的输入是否正确
  let user = await UserModel.findOne({ username: username, pwd: md5(pwd) });
  //如果不正确, 响应数据有误
  if (!user) {
    res.json({
      msg: "账号或密码错误",
      data: null,
      code: "1007",
    });
    
  } else {
    //如果正确, 设置 token 信息
    let token = createToken({_id: user._id, username: user.username});
    //设置响应
    res.json({
      msg: "登录成功",
      data: token,
      code: "2000",
    });
  }
});

//暴露
module.exports = router;
